<!--
 * @Author: your name
 * @Date: 2022-03-28 15:16:08
 * @LastEditTime: 2022-03-28 15:16:08
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \macc.admin.vue\src\views\system\logo\index.vue
-->

<template>
  <div>
    <rj-modal
      title="设置LOGO"
      :visible="logovisible"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      okText="确定"
      cancelText="取消"
    >
      <a-form-model
        :model="form"
        :wrapper-col="{ span: 23 }"
        :rules="rules"
        ref="form"
      >
        <a-form-model-item prop="tenantName">
          <label>名称</label>
          <a-input v-model="form.tenantName" />
        </a-form-model-item>
        <a-form-model-item>
          <label style="margin-right: 2px">LOGO</label>
          <a-upload
            :multiple="false"
            list-type="picture-card"
            :show-upload-list="false"
            :fileList="fileList"
            class="avatar-uploader"
            :before-upload="beforeUpload"
            :accept="accept.toString()"
          >
            <img
              v-if="fileUrl"
              :src="fileUrl"
              width="100px"
              height="100px"
              style="border-radius: 50%"
              alt="avatar"
              @error="handelImgErr"
            />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-model-item>
        <div class="txtHint">
          <p>为使LOGO较好的呈现效果,不变形,请上传60×60规格的图片</p>
          <p>仅支持png,jpg,jpeg,bmp的图片格式</p>
          <p style="color: #ff9b00">图片大小不超过1M</p>
        </div>
      </a-form-model>
    </rj-modal>
  </div>
</template>

<script>
import {
  requestHttp,
  maccApi,
  requestHttpDownload,
  requestHttpUpload,
} from '@utils/index';

export default {
  name: 'LOGO',
  props: {
    logovisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      form: {
        tenantName: '',
        tenantId: '',
      },
      fileName: '',
      fileUrl: '',
      fileList: [],
      loading: false,
      accept: ['.jpg', '.jpeg', '.bmp', '.png'],
      rules: {
        tenantName: [
          {
            required: true,
            max: 64,
            message: '名称长度不能超过64位',
            trigger: 'change',
          },
        ],
      },
    };
  },
  created() {
    this.getTenantInfo();
  },
  mounted() {},
  destroyed() {
    this.$EventBus.$off('LOGO_UPDATE');
  },
  methods: {
    async getTenantInfo() {
      var data = {
        api: maccApi.GET_USER_LOGO_API,
        method: 'GET',
      };
      let res = await requestHttp(data);
      if (res && res.code == 0) {
        this.form.tenantName = res.tenantName;
        this.form.tenantId = res.tenantId;
        // this.getLogoImg();
      }
    },
    async getLogoImg() {
      const api = `${maccApi.TENANT_LOGO_GET_API}?id=${this.form.tenantId}`;
      const data = await requestHttpDownload({
        api: api,
        method: 'GET',
        attachment: true,
        module: 'default',
        fileName: 'test.jpg',
        contentType: 'application/image;charset=UTF-8',
      });
      //debugger;
      let downloadData = data.data.downloadData;
      const imgsrc =
        '/webproxy/common/file/download' + ('?downloadData=' + downloadData);
      this.fileUrl = imgsrc;
    },
    handleOk() {
      const fileNames = this.fileName.split('.') || '';
      const fileType = '.' + fileNames[fileNames.length - 1];
      const fileNameCoding = encodeURIComponent(this.fileName + fileType);
      const api =
        this.fileList.length == 0
          ? `${maccApi.TENANT_LOGO_POST_API}?tenantName=${encodeURI(
              this.form.tenantName
            )}`
          : `${maccApi.TENANT_LOGO_POST_API}?tenantName=${encodeURI(
              this.form.tenantName
            )}&fileName=${fileNameCoding}`;

      if (this.fileList.length === 0) {
        const par = {
          api,
          method: 'POST',
        };
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            let res = await requestHttp(par);
            if (res && res.code == 0) {
              console.log('success');
              this.$emit('hideLogo');
              this.$EventBus.$emit('LOGO_UPDATE');
              this.$message.success('操作成功');
            } else {
              this.$message.error(res.msg);
            }
          }
        });
      } else {
        const params = {
          file: this.fileList[0],
          uploadData: JSON.stringify({
            api,
            method: 'POST',
            contentType: 'application/octet-stream', //此接口必须设置contentType
          }),
        };
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const { code, msg } = await requestHttpUpload(params);
            if (code == 0) {
              this.$message.success('操作成功');
              this.$EventBus.$emit('LOGO_UPDATE');
              this.$emit('hideLogo');
            } else {
              this.$message.warning(msg);
            }
          }
        });
      }
    },
    handleCancel() {
      this.$emit('hideLogo');
    },
    beforeUpload(file) {
      //判断文件格式
      console.log(file, 'file');
      debugger;
      const fileNames = file.name.split('.') || '';
      const fileType = '.' + fileNames[fileNames.length - 1];
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error('图片大小不超过1M');
        return false;
      }
      if (this.accept.indexOf(fileType) > -1) {
        this.fileName = file.name;
        this.fileUrl = window.URL.createObjectURL(file);
        this.fileList = [file];
        console.log(this.fileList, 'this.fileList');
        console.log(this.fileUrl, 'uploadfileUrl');
        //自定义上传
      } else {
        this.$message.warning('上传文件类型错误');
      }

      return false;
    },
    handelImgErr() {
      console.log('图片加载失败。。。。。');
      this.fileUrl =
        '';
    },
  },
};
</script>

<style scoped lang="less">
::v-deep .ant-form-item-children {
  display: flex;
  align-items: center;
}
.ant-form-item label {
  font-weight: 700;
  width: 50px;
}
::v-deep .ant-upload.ant-upload-select-picture-card {
  border-radius: 50%;
}
.txtHint {
  font-size: 12px;
  line-height: 1;
  color: #ccc;
}
::v-deep .has-error .ant-form-explain,
.has-error .ant-form-split {
  padding-left: 45px;
}
</style>
